// 用户相关的二级仓库
// 导入 defineStore 方法
import { defineStore } from "pinia";
// 引入接口
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
import type { UserState } from "./types/type";
import type {
  loginFormData,
  LoginResponseData,
  userInfoResponseData,
} from "@/api/user/type";
// 引入操作本地存储的工具文件
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
// 引入路由
import { constantRoute, asyncRoute, anyRoute } from "@/router/routes";
import router from "@/router";
// 引入深拷贝工具
import { cloneDeep } from "lodash";
// 创建用户相关的二级仓库
const useUserStore = defineStore("UserStore", {
  // 仓库数据存储
  state: (): UserState => {
    return {
      token: GET_TOKEN(), // 用户唯一标识 token
      menuRoutes: constantRoute, // 动态生成菜单的路由
      username: "",
      avatar: "",
    };
  },
  actions: {
    // 用户登陆的方法
    async userLogin(data: loginFormData) {
      const result: LoginResponseData = await reqLogin(data);
      if (result.code == 200) {
        // 仓库存储token
        this.token = result.data as string;
        // 本地存储持久化存储
        SET_TOKEN(result.data as string);
        // 保证当前async函数返回一个成功的promise
        return "ok";
      } else {
        return Promise.reject(new Error(result.data));
      }
    },
    // 获取用户信息的方法
    async userInfo() {
      // 获取用户信息存储在仓库中
      const result: userInfoResponseData = await reqUserInfo();
      if (result.code === 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        const userRoute = [...constantRoute, ...anyRoute, ...filterAsyncRoute(cloneDeep(asyncRoute), result.data.routes)]
        this.menuRoutes = [...userRoute];
        [...userRoute, anyRoute].forEach((item: any) => {
          router.addRoute(item);
        })
        return "ok";
      } else {
        return Promise.reject("获取用户信息失败");
      }
    },
    // 退出登录的方法
    async userLogout() {
      const result: any = await reqLogout();
      if (result.code === 200) {
        this.token = "";
        this.username = "";
        REMOVE_TOKEN();
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
  },
  getters: {},
});

// 过滤当前用户要展示的异步路由
const filterAsyncRoute = (asyncRoute: any, routes: any) => {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}

// 暴露获取仓库的方法
export default useUserStore;
